package me.zhengjie.modules.website.repository;

import me.zhengjie.modules.website.domain.Topics;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author system
 * @since 2024-12-02 17:12:28
 */
@Component
public class TopicsSpecifications {

    public static Specification<Topics> queryList(Topics topics) {
        return (root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (topics.getId() != null) {
                predicates.add(builder.equal(root.get("id" ).as(Long.class), topics.getId()));
            }
            if (topics.getTitle() != null) {
                predicates.add(builder.like(root.get("title" ).as(String.class), "%" + topics.getTitle() + "%" ));
            }
            if (topics.getCoverImage() != null) {
                predicates.add(builder.like(root.get("coverImage" ).as(String.class), "%" + topics.getCoverImage() + "%" ));
            }
            if (topics.getDescription() != null) {
                predicates.add(builder.like(root.get("description" ).as(String.class), "%" + topics.getDescription() + "%" ));
            }
            if (topics.getStatus() != null) {
                predicates.add(builder.equal(root.get("status" ).as(Integer.class), topics.getStatus()));
            }
            if (topics.getSortOrder() != null) {
                predicates.add(builder.equal(root.get("sortOrder" ).as(Integer.class), topics.getSortOrder()));
            }
            Predicate[] p = new Predicate[predicates.size()];
            return query.where(builder.and(predicates.toArray(p))).getRestriction();
        };
    }

}
